import LTRes from "./utils/LTRes";
import { LoadUIPack } from "./utils/LoadUIPack";
import UI_Main from "./ui/Main/UI_Main";
import MainBinder from "./ui/Main/MainBinder";
import { BaseSample } from "./samples/BaseSample";
import { BasicTest } from "./samples/BasicTest";

export class Main {

    constructor() {
        let config3D = new Config3D();
        config3D.octreeCulling = false;
        config3D.enableMultiLight = false;
        config3D.isAntialias = true;

        Laya3D.init(750, 1334, config3D, Laya.Handler.create(this, this._OnInitFinished));
    }

    private async _OnInitFinished() {
        Laya.stage.screenMode = Laya.Stage.SCREEN_VERTICAL;
        Laya.stage.scaleMode = Laya.Stage.SCALE_FIXED_AUTO;
        Laya.stage.alignV = Laya.Stage.ALIGN_MIDDLE;
        Laya.stage.alignH = Laya.Stage.ALIGN_CENTER;
        //兼容微信不支持加载scene后缀场景
        Laya.URL.exportSceneToJson = true;
        Laya.Stat.show();
        Laya.alertGlobalError(false);

        this._CreateUI();
    }

    private _samples: BaseSample[] = [
        new BasicTest()
    ];

    private _currentSample: BaseSample;

    private async _CreateUI() {
        fgui.UIConfig.packageFileExtension = "bin";
        Laya.stage.addChild(fgui.GRoot.inst.displayObject);
        MainBinder.bindAll();

        let urls: any[] = [];
        let uiPack = new LoadUIPack("res/Main", 0);
        uiPack.PushUrl(urls);
        await LTRes.Load2dAsync(urls);
        uiPack.AddPackage();

        let ui = fgui.GRoot.inst.addChild(UI_Main.createInstance()) as UI_Main;
        ui.m_list_func.setVirtual();
        ui.m_list_func.itemRenderer = Laya.Handler.create(this, this._ItemRender, null, false);
        ui.m_list_func.numItems = this._samples.length;

        this._currentSample = this._samples[0];
        this._currentSample.Init();

        Laya.timer.frameLoop(1, this, this._LogicUpdate);
    }

    private _ItemRender(index: number, itemUI: fgui.GButton) {
        let data = this._samples[index];
        itemUI.text = data.name;
        itemUI.onClick(this, this._OnClickItem, [index]);
    }

    private _OnClickItem(index: number) {
        let data = this._samples[index];
        if (data == this._currentSample) return;
        this._currentSample.Clear();
        this._currentSample = data;
        this._currentSample.Init();
    }


    private _LogicUpdate() {
        let dt = Laya.timer.delta / 1000;
        dt = 1/60;
        this._currentSample.LogicUpdate(dt);
    }

}

new Main();